<template>
  <div id="app">
    <cart-item
      :list="list"
      @onItemChange="onItemChange"
      @addItem="addItem"
      @removeItem="removeItem"
    ></cart-item>
    <!-- <TotalPrice></TotalPrice> -->
    <total-price
      :allChecked="allChecked"
      :totalPrice="totalPrice"
      @onAllChecked="onAllChecked"
    ></total-price>
  </div>
</template>

<script>
import axios from 'axios'
import CartItem from './components/CartItem.vue'
import TotalPrice from './components/TotalPrice.vue'
export default {
  name: 'App',
  components: { CartItem, TotalPrice },
  data() {
    return {
      allChecked: false,
      opt: {
        page: 1,
        size: 3,
      },
      list: [],
    }
  },
  created() {
    this.getData()
  },
  computed: {
    totalPrice() {
      return this.list.reduce((num, item) => {
        return num + item.count * item.price
      }, 0)
    },
  },
  methods: {
    async getData() {
      const res = await axios.get('/api/list', { params: this.opt })
      console.log(res.data.data.list)
      this.list = res.data.data.list
    },
    addItem(item) {
      item.count++
    },
    removeItem(item) {
      if (item.count <= 1) {
        if (window.confirm('确定删除吗？')) {
          const removeIndex = this.list.findIndex((v) => v.id === item.id)
          this.list.splice(removeIndex, 1)
        }
        return
      }
      item.count--
    },
    // 全选 反选
    onAllChecked() {
      this.allChecked = !this.allChecked
      console.log(this.allChecked, 'alll')
      this.list.forEach((item) => {
        item.check = this.allChecked
      })
    },
    onItemChange(item) {
      item.check = !item.check
      this.allChecked = this.list.every((v) => {
        return v.check
      })
    },
  },
}
</script>

<style lang="scss">
* {
  margin: 0;
  padding: 0;
  list-style: none;
}
.cart-item {
  display: flex;
  li {
    padding: 5px;
    margin: 5px;
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.btn {
  margin: 5px;
  padding: 5px;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 5px;
}
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
